package com.security.Filter.MobileCaptchaFilter;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

public class MobileCapchaAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    protected UserDetailsService getUserDetailsService() {
        return this.userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileCapchaAuthenticationToken mobileToken = (MobileCapchaAuthenticationToken)authentication;
        UserDetails userDetails = userDetailsService.loadUserByUsername(mobileToken.getPrincipal().toString());
        if (userDetails==null){
            throw new InternalAuthenticationServiceException("无法根据手机号获取用户信息");
        }
        MobileCapchaAuthenticationToken mobileTokenResult = new MobileCapchaAuthenticationToken(userDetails,userDetails.getAuthorities());
        mobileTokenResult.setDetails(mobileToken.getDetails());
        return mobileTokenResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return MobileCapchaAuthenticationToken.class.isAssignableFrom(aClass);
    }
}

